package com.gy.service.impl;

import com.gy.service.NoticeService;
import com.gy.vo.NoticeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class CacheUpdateService {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private NoticeService noticeService;

    // 创建一个 ReentrantLock
    private final Lock lock = new ReentrantLock();

    @Async
    public void refreshCacheAsync() {
        Cache cache = cacheManager.getCache("latestNotices");

        if (cache == null || isCacheExpired(cache)) {
            if (lock.tryLock()) {
                try {
                    // 获取最新的公告数据
                    List<NoticeVO> latestNotices = noticeService.getLatestNotices();
                    // 更新缓存
                    cacheManager.getCache("latestNotices").put("latest", latestNotices);
                    log.info("Cache updated with new notices asynchronously.");
                } finally {
                    // 确保锁被释放
                    lock.unlock();
                }
            } else {
                // 如果其他线程正在更新缓存，则跳过更新
                log.info("Cache refresh skipped as another thread is updating the cache.");
            }
        } else {
            log.info("Cache is not expired. Skipping refresh.");
        }
    }

    /**
     * 判断缓存是否已经过期
     * 这里简单示例通过缓存中存储的过期时间来判断
     * @param cache 缓存对象
     * @return true 如果缓存过期
     */
    private boolean isCacheExpired(Cache cache) {
        if (cache == null) {
            return true;
        }

        // 获取缓存中保存的过期时间（可以通过实际需要的方式进行扩展）
        Long lastUpdatedTime = cache.get("lastUpdatedTime", Long.class);
        if (lastUpdatedTime == null) {
            return true; // 默认认为缓存过期
        }

        long currentTime = System.currentTimeMillis();
        long cacheExpireDuration = 5 * 60 * 1000;  // 假设缓存过期时间为5分钟

        return (currentTime - lastUpdatedTime) > cacheExpireDuration;
    }
}
